#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int trap(vector<int>& height)
{
    int n = height.size();
    int res = 0;
    if(n>0)
    {
        int l = 0, r = n-1;
        int lh = height[l], rh = height[r];
        while(l<=r)
        {
            if(lh<rh)
            {
                res += max(lh-height[l],0);
                l++;
                if(l<=n-1&&height[l]>lh) lh = height[l];
            }
            else
            {
                res+= max(rh-height[r],0);
                r--;
                if(r>=0 && height[r]>rh) rh = height[r];
            }
        }
    }
    return res;
}
int main(int argc, char const *argv[])
{
    vector<int> height;
    freopen("test.txt","r",stdin);
    int N; cin>>N;
    int tmp;
    for(int i =0;i<N;++i)
    {
        cin>>tmp;
        height.push_back(tmp);
    }
    int res = trap(height);
    cout<<res;
    return 0;
}
